# -*- coding: utf-8 -*-
import os,sys,datetime


class DefaultConfig:
    # Python version
    py_version = '{0.major}{0.minor}'.format(sys.version_info)
    FLASK_ADMIN_FLUID_LAYOUT = True
    DEBUG = False
    TESTING = False
    SECRET_KEY = os.environ.get('SECRET_KEY','^\xb5\xf8\xae\x94\xd1e\xf1\x0b\xbd\x1erWC\x93\xc4\xb3y\xabz\x03\x18?\x1e')
    MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
    MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
    MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS', 'true').lower() in ['true', 'on', '1']
    MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
    MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
    SSL_REDIRECT = False
    # 如果设置成 True (默认情况)，Flask-SQLAlchemy 将会追踪对象的修改并且发送信号。这需要额外的内存， 如果不必要的可以禁用它。
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    # 如果设置成 True，SQLAlchemy 将会记录所有 发到标准输出(stderr)的语句，这对调试很有帮助。
    SQLALCHEMY_ECHO = False
    # ＃ 服务器名称
    #      ＃服务器的名称和端口号。
    #      ＃需要子域支持（例如：“ myapp.dev:5000”）和
    #      ＃在没有请求上下文但有应用程序上下文的情况下生成URL
    #      ＃生成URL（使用celery应用程序）所需的＃
    #      ＃注意localhost不支持子域，因此将其设置为
    #      ＃“ localhost”没有帮助。
    #      ＃FlaskBB论坛的示例：SERVER_NAME =“ forums.flaskbb.org”
    # SERVER_NAME =
    # url方案。 在生产环境中， 建议使用'https'。 会影响使用'url_for'生成的url
    PREFERRED_URL_SCHEME = "http"
    # ＃您可以使用与生成WTF_CSRF_SECRET_KEY相同的方法
    #      ＃生成了SECRET_KEY。 如果没有提供WTF_CSRF_SECRET_KEY，它将
    #      ＃使用SECRET_KEY。
    WTF_CSRF_ENABLED = True
    WTF_CSRF_SECRET_KEY = "\xc6F\xcf\xd7Mz\xc5\x0c-\xad\x89\xa3+\xe5\xb8\xb7\xaf\xcef\x1d\xf5r\x10\x88"

    # The name of the cookie to store the “remember me” information in. cookie名称
    REMEMBER_COOKIE_NAME = "remember_token"
    # The amount of time before the cookie expires, as a datetime.timedelta object.
    REMEMBER_COOKIE_DURATION = datetime.timedelta(days=365)
    # 如果“记住我” cookie应该跨域，
    #      ＃在此处设置域值（即.example.com将允许Cookie
    #      ＃用于example.com的所有子域）。
    REMEMBER_COOKIE_DOMAIN = None
    # Limits the “Remember Me” cookie to a certain path.    cookie 存储路径
    REMEMBER_COOKIE_PATH = "/"
    # Restricts the “Remember Me” cookie’s scope to secure channels (typically HTTPS). 将“记住我” cookie的范围限制为安全通道（通常为HTTPS）。
    REMEMBER_COOKIE_SECURE = None
    # Prevents the “Remember Me” cookie from being accessed by client-side scripts. 防止客户端脚本访问“记住我” cookie。
    REMEMBER_COOKIE_HTTPONLY = False

    basedir = os.path.abspath('.')

    # Flask-Security config
    SECURITY_URL_PREFIX = "/"
    SECURITY_PASSWORD_HASH = "pbkdf2_sha512"
    SECURITY_PASSWORD_SALT = "\xfd\xa4\nVe\xa3\x05}\xb0\x0f\xa6\x88\xbc\xe9\x1bKk`\x8a\xe2\xa7\xf9\xf51"

    # Flask-Security URLs, overridden because they don't put a / at the end
    SECURITY_LOGIN_URL = "/login/"
    SECURITY_LOGOUT_URL = "/logout/"
    SECURITY_REGISTER_URL = "/register/"

    SECURITY_POST_LOGIN_VIEW = "/"
    SECURITY_POST_LOGOUT_VIEW = "/"
    SECURITY_POST_REGISTER_VIEW = "/"
    CLIENT_CONFIG = os.path.join(basedir, 'monclient','config.json')
    # Flask-Security features
    SECURITY_REGISTERABLE = False
    SECURITY_SEND_REGISTER_EMAIL = False
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    REDIS_ENABLED = True
    MACHINE_NIC_RATE = "machine:{}:nic:{}:rate"      # 第1个参数 设备ID system-uuid  第二个网卡名称

    RD_WILL_TASK_ID = "monclient:will_task_id"  # 下发给客户端的任务列表
    RD_MACHINE_EXISTS = "monclient:{}:exists"  # 存在时1 否则是0
    RD_TASK = "monclient:{}:task"  # 下发给客户端的任务列表
    RD_DEF_NETIO = "monclient:{}:default_rx_tx"  # 10秒过期
    RD_TASK_RESULT = "monclient:task_result"  # 客户端推送的任务结果或报警信息等
    RD_MACHINE_MARK_SYSTEM = "monclient:machine_mark:system:{}"  # 设备信息的 标识，接收后写入
    RD_MACHINE_WARN_QUEUE = "monclient:warn_queue"      # 等待发送警告信息到设备的 任务队列，保存警告记录ID
    RD_FLOW_DATA_LIST = "monclient:tempflowdata"  # 客户端推送的实时上下行带宽队列，所有设备的,用于暂时保存，填充到数据库及提取95计费点
    RD_LAST_NINE_FIVE_TIME = "monclient:lastninefiveflowdatatime"  # 上次提取95计费点时间
    RD_LAST_CLEAR_BAND_WIDTH_DATA_TIME = "monclient:lastclearbandwidthtime"  # 上次清理 速率记录时间
    RD_WEIXIN_CFG = "monserver:weixin_cfg"
    RD_WARN_CONFIRM = "monserver:warn_confirm:{}"

    #region 日志配置
    # 若此项设置为路径,请将 USE_DEFAULT_LOGGING设置为False 否则日志配置文件之间可能存在交互
    # 如果设置为文件路径，则应为绝对文件路径
    LOG_CONF_FILE = None
    # 存储Info和Error日志的路径 路径必须是绝对路径
    LOG_PATH = os.path.join(basedir, 'logs')
    LOG_DEFAULT_CONF = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format': '%(asctime)s %(levelname)-7s %(name)-25s %(message)s'
            },
            'advanced': {
                'format': '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
            }
        },

        'handlers': {
            'console': {
                'level': 'NOTSET',
                'formatter': 'standard',
                'class': 'logging.StreamHandler',
            },
            'noveldatasource': {
                'level': 'DEBUG',
                'formatter': 'standard',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(LOG_PATH, 'noveldatasource.log'),
                'mode': 'a',
                'maxBytes': 10485760,  # 10MB
                'backupCount': 5,
            },
            'infolog': {
                'level': 'INFO',
                'formatter': 'standard',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(LOG_PATH, 'info.log'),
                'mode': 'a',
                'maxBytes': 10485760,  # 10MB
                'backupCount': 5,
            },
            'errorlog': {
                'level': 'ERROR',
                'formatter': 'standard',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(LOG_PATH, 'error.log'),
                'mode': 'a',
                'maxBytes': 10485760,  # 10MB
                'backupCount': 5,
            }
        },

        'loggers': {
            'adminApp': {
                'handlers': ['infolog', 'errorlog'],
                'level': 'ERROR',
                'propagate': True
            },
            'noveldatasource': {
                'handlers': ['console', 'noveldatasource'],
                'level': 'WARNING',
                'propagate': True
            },
        }
    }

    # 是否启用默认日志
    USE_DEFAULT_LOGGING = True

    # 是否将日志发送到管理员邮箱
    SEND_LOGS = False
    #endregion
    SEND_LOGS_TE = True

    DATA_GZ_PATH = os.path.join(basedir, 'data_gzip')

    @staticmethod
    def init_app(app):
        logpath = app.config.get('LOG_PATH')
        if logpath and not os.path.exists(logpath):
            os.makedirs(logpath)


class DevelopmentConfig(DefaultConfig):
    SQLALCHEMY_DATABASE_URI = 'mssql+pymssql://sa:123456@localhost:1433/monserverdata?charset=utf8'
    # SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://monserverdata:monserverdata@192.168.3.100:3306/monserverdata?charset=utf8'
    SQLALCHEMY_POOL_SIZE = 50
    SQLALCHEMY_POOL_TIMEOUT = 20
    SQLALCHEMY_POOL_RECYCLE = -1
    DEBUG = True
    REDIS_URL = "redis://:123456@localhost:6379/2"
    # REDIS_URL = "redis://:@localhost:6379/2"
    # REDIS_URL = "redis://:682321@192.168.231.143:6379/0"
    REDIS_DATABASE = 0


class TestingConfig(DefaultConfig):
    DEBUG = True
    TESTING = True
    WTF_CSRF_ENABLED = False
    SSQLALCHEMY_DATABASE_URI = 'mysql+pymysql://monserverdata:monserverdata@192.168.231.143:3306/monserverdata?charset=utf8'
    REDIS_URL = "redis://:682321@192.168.231.143:6379/0"
    REDIS_DATABASE = 0


class ProductionConfig(DefaultConfig):
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://monserverdata:hRTFePSJr4pTcDWY@localhost:3306/monserverdata?charset=utf8'
    SQLALCHEMY_POOL_SIZE = 50
    SQLALCHEMY_POOL_TIMEOUT = 20
    SQLALCHEMY_POOL_RECYCLE = -1
    REDIS_URL = "redis://:AtY68232@127.0.0.1:6379/6"
    REDIS_DATABASE = 0


Config = {
    'development': DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,
    'default': ProductionConfig
}